﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;


namespace getSongs {
    public partial class Form1 : Form {

        List<string> fileList = new List<string>();
        BackgroundWorker worker = new BackgroundWorker();

        public Form1() {
            InitializeComponent();
            radTextBox2.Text = @"http://www.littleducks.cn/ergeflash/yingwenerge";
            worker.WorkerReportsProgress = true;
            worker.DoWork += (s, e) => {
                string path = (string)e.Argument;
                int count = 0;
                foreach (string filename in fileList) {
                    using (WebClient client = new WebClient()) {
                        string url = @"http://www.littleducks.cn" + filename;
                        string[] temp = filename.Split('/');
                        string saveFile =Path.Combine(path, temp.Last());
                        client.DownloadFile(url, saveFile);
                        count++;
                    }
                    float percent = (float)count / (float)fileList.Count * 100f;
                    worker.ReportProgress((int)percent);
                }
            };
            worker.ProgressChanged += (s, e) => {
                this.radProgressBar1.Value1 = e.ProgressPercentage;
            };
            worker.RunWorkerCompleted += (s, e) => {
                MessageBox.Show("OK");
            };
        }

        private void radButton1_Click(object sender, EventArgs e) {
            string html = null;
            if (getweb(radTextBox2.Text, out html)) {
                this.radTextBox1.Text = html;
                radListView1.DataSource= getLinksCollection(html);
                radListView2.DataSource = fileList;
            }
        }

        public List<string> getLinksCollection(string html) {
            MatchCollection matches = Regex.Matches(html, "href='([^\"]*?)'.class='preview'.", RegexOptions.IgnoreCase);
            List<string> result = new List<string>();
            foreach (Match x in matches) {
                string s = x.Groups[1].Value;
                result.Add(s);
                string subpageHTML = null;

                if (getweb("http://www.littleducks.cn" + s, out subpageHTML)) {
                    Match m = Regex.Match(subpageHTML, @"var\s+url\s+=\s+""([^""]*?)""", RegexOptions.IgnoreCase);
                    string file = m.Groups[1].Value;
                    fileList.Add(file);
                }
                
            }
            return result;
        }

        private bool getweb(string strURL, out string buf) {
            buf = "";
            try {
                //Uri url=new Uri(strURL,false);
                HttpWebRequest request;
                request = (HttpWebRequest)WebRequest.Create(strURL);
                request.Method = "POST"; //Post请求方式
                request.ContentType = "text/html;charset=utf-8"; //内容类型
                string paraUrlCoded = System.Web.HttpUtility.UrlEncode(""); //参数经过URL编码
                byte[] payload;
                payload = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(paraUrlCoded); //将URL编码后的字符串转化为字节 
                request.ContentLength = payload.Length; //设置请求的ContentLength
                Stream writer = request.GetRequestStream(); //获得请求流
                writer.Write(payload, 0, payload.Length); //将请求参数写入流
                writer.Close(); //关闭请求流
                HttpWebResponse response;
                response = (HttpWebResponse)request.GetResponse(); //获得响应流
                Stream s;
                s = response.GetResponseStream();
                StreamReader objReader = new StreamReader(s, System.Text.Encoding.GetEncoding("GB2312"));
                string HTML = "";
                string sLine = "";
                int i = 0;
                while (sLine != null) {
                    i++;
                    sLine = objReader.ReadLine();
                    if (sLine != null)
                        HTML += sLine;
                }
                //HTML = HTML.Replace("&lt;","<");
                //HTML = HTML.Replace("&gt;",">");
                buf = HTML;
                return true;
            } catch (Exception x) {
                buf = x.Message.ToString();
                return false;
            }
        }

        

        private void radButton2_Click(object sender, EventArgs e) {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.ShowNewFolderButton = true;
            if (dialog.ShowDialog()== System.Windows.Forms.DialogResult.OK) {
                worker.RunWorkerAsync(dialog.SelectedPath);
            }
        }
    }
}
